package com.sc.basic.service.impl;

import com.sc.basic.entity.City;
import com.sc.basic.entity.CityList;
import com.sc.basic.service.CityDataService;
import com.sc.basic.util.XmlBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author shuchang
 * @Date 2018/3/16 下午4:37
 */
@Service
@Slf4j
public class CityDataServiceImpl implements CityDataService{

    @Override
    public List<City> listCity() {
        //读取xml文件
        ClassPathResource resource = new ClassPathResource("citylist.xml");
        StringBuffer buffer = new StringBuffer();
        CityList cityList = new CityList();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(),"utf-8"));

            String line = "";
            while ((line=reader.readLine())!=null){
                buffer.append(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //xml转java pojo
        try {
            cityList = (CityList) XmlBuilder.xmlStr2Obj(CityList.class,buffer.toString());
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cityList.getCityList();
    }
}
